<template>
  <div id="SelectItemList">
    <vxe-pulldown :ref="`pulldownRef${compId}`" transfer>
      <template #default>
        <vxe-input ref="SelectInpiut" v-model="inputValue" suffix-icon="vxe-icon-table" placeholder="请选择检测项目" @suffix-click="suffixClick" @focus="focusEvent" @blur="blurEvent" @keydown="keyupEvent4" @input="inputChange" @dblclick.native.prevent="inputdblClick"></vxe-input>
      </template>

      <template #dropdown>
        <div class="my-bodydown4" :style="{ width: width, height: height }">
          <vxe-grid border :ref="'gridTable4' + compId" :auto-resize="true" height="auto" width="auto" :row-config="{ isHover: true, isCurrent: true }" :keyboard-config="{ isArrow: true, isEnter: true }" :loading="sLoading" :data="dataList" :columns="column" :pager-config="isPage ? tablePage : null" :edit-config="{ mode: 'row' }" :column-config="{ resizable: false }" @cell-click="cellClickEvent" @page-change="pageChangeEvent">
          </vxe-grid>
        </div>
      </template>
    </vxe-pulldown>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { pageSizes, IsEmpty, newGuid } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
defineExpose({
  findDataList
});
let compId: string = newGuid();
let props = defineProps({
  url: String, //请求地址
  column: Array as () => String[], //动态列和字段名
  searchParam: {}, //接口参数{key1:value1,key2:value2...}
  isPage: { type: Boolean, default: false }, //是否需要分页
  width: { type: String, default: '590px' }, //表格宽度
  height: { type: String, default: '300px' }, //表格高度
  inputKeyName: String, //查询入参名称
  placeholder: { type: String, default: '点击选择' } //弹框标题
}) as any;
let inputValue = ref(null);
let sLoading = ref(false);
let { proxy }: any = getCurrentInstance();
let dataList = reactive([]);
let tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: pageSizes[0]
});
let enterCount = ref(0);
let searchValue = ref(null);
// 输入框获取焦点
let pulldownRef = ref();
let SelectInpiut = ref();
let isAllowClick = ref(true);
let enterValue = 0;


function findDataList() {
  dataList.length = 0;
  sLoading.value = true;
  // 请求参数
  let params: any = {};

  // 循环父组件传来的参数，添加到参数对象中(data，params)
  if (!IsEmpty(props.searchParam)) {
    for (const key in props.searchParam) {
      if (props.searchParam[key]) {
        params[key] = props.searchParam[key];
      }
    }
  }

  if (!IsEmpty(props.inputKeyName)) {
    params[props.inputKeyName] = inputValue.value;
  }

  if (!IsEmpty(searchValue.value) && searchValue.value != null) {
    params['searchValue'] = searchValue.value.toUpperCase();
  } else {
    params['searchValue'] = '';
  }

  if (!IsEmpty(inputValue.value) && inputValue.value != null) {
    params['searchValue'] = inputValue.value.toUpperCase();
  } else {
    params['searchValue'] = '';
  }

  proxy.$http
    .get(props.url, { params })
    .then((res: any) => {
      sLoading.value = false;
      if (res.status.code !== 1 && res.status.code !== 200) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else {
        dataList.length = 0;
        if (props.isPage) {
          dataList.push(...res.data.records);
          tablePage.total = res.data.total;
        } else {
          dataList.push(...res.data);
          if (dataList.length > 0) {
            const $grid = proxy.$refs['gridTable4' + compId];
            if ($grid) {
              $grid.setCurrentRow(dataList[0]);
              $grid.focus();
            }
          }
        }
      }
    })
    .catch((err) => {
      sLoading.value = false;
      VxeMessage('获取列表失败', VxeNotifyType.error);
    });
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.showPanel();
  }
  searchValue.value = null;
}
//装饰器中的参数是方法名，用来传递给父组件
function handleClickRow({ row }) {
  proxy.$emit('selectDataRow', row);
}

/**
 * 文本框输入内容改变
*/
function inputChange(e: any) {
  enterCount.value = 1;
}

function focusEvent() {
  // const $pulldown = pulldownRef.value;
  // if ($pulldown) {
  //   $pulldown.showPanel();
  // }

}
/**
 * 文本框双击事件
 */
function inputdblClick(e) {
  const $pullDown = proxy.$refs['pulldownRef' + compId];
  if ($pullDown) {
    $pullDown.showPanel();
  }
  findDataList();
}
// 输入框点击
function suffixClick() {
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.togglePanel();
  }
}

// 点击表格当前行
async function cellClickEvent({ row }) {
  if (!isAllowClick.value) {
    return;
  }
  isAllowClick.value = false;
  if (!isAllowClick.value) {
    proxy.$emit('SelectCellClick', row);
  }
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.togglePanel();
  }
  inputValue.value = row.name;
  setTimeout(() => {
    isAllowClick.value = true;
  }, 1000);
}


//?键盘输入改变
function keyupEvent4({ value, $event }: any) {
  if ($event.keyCode === 13 && enterValue <= 1) {
    if (!IsEmpty(value)) {
      searchValue.value = value;
    }
    const $pullDown = proxy.$refs['pulldownRef' + compId];
    if ($pullDown) {
      $pullDown.showPanel();
    }
    findDataList();
    enterValue = 2;
    return;
  }

  if ($event.keyCode === 13 && enterValue === 2) {
    const $grid = proxy.$refs['gridTable4' + compId];
    if ($grid) {
      const rObj = $grid.getCurrentRecord();
      proxy.$emit('SelectCellClick', rObj);
      const downExmItemEle = proxy.$refs[`pulldownRef${compId}`] as any;
      if (downExmItemEle.isPanelVisible()) {
        downExmItemEle.hidePanel();
      }
    }
    enterValue = 0;
  } else {
    if ($event.keyCode === 13 || $event.keyCode === 33 || $event.keyCode === 34 || $event.keyCode === 37 || $event.keyCode === 38 || $event.keyCode === 39 || $event.keyCode === 40) {
      return; //TAG1回车键直接返回，不做处理
    }
    const downExmItemEle = proxy.$refs[`pulldownRef${compId}`] as any;
    if (!downExmItemEle.isPanelVisible()) {
      return;
    }
    findDataList();
    enterValue = 0;
  }
}


// 输入框失去焦点
function blurEvent() {
  const $pulldown = pulldownRef.value;
  if ($pulldown) {
    $pulldown.showPanel();
  }
}

// 页数变更
function pageChangeEvent({ type, currentPage, pageSize }) {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  findDataList();
}
</script>
<style lang="scss" scoped>
#SelectItemList {
  // :deep(.vxe-table) {
  //   .vxe-body--row {
  //     .vxe-body--column {
  //       .vxe-cell {
  //         line-height: 19px !important;
  //         margin-left: 1px !important;
  //       }
  //     }
  //   }
  // }
  :deep(.vxe-table--render-default .vxe-cel) {
    line-height: 19px !important;
  }
}

// :deep(.vxe-body--row) {
//   line-height: 19px !important;
//   margin-left: 1px !important;
// }
</style>
